package cn.wolfcode.luowowo.comment.service.impl;

import cn.wolfcode.luowowo.comment.domain.StrategyComment;
import cn.wolfcode.luowowo.comment.query.StrategyCommentQuery;
import cn.wolfcode.luowowo.comment.repository.StrategyCommentRepository;
import cn.wolfcode.luowowo.comment.service.IStrategyCommentService;
import cn.wolfcode.luowowo.common.util.LogicException;
import com.alibaba.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.Date;
import java.util.List;

@Service
public class StrategyCommentServiceImpl implements IStrategyCommentService {

    @Autowired
    private StrategyCommentRepository repository;

    @Autowired
    private MongoTemplate template;


    //存入用户评论
    public void save(StrategyComment strategyComment) {
        strategyComment.setCreateTime(new Date());
        repository.save(strategyComment);
    }

    public Page query(StrategyCommentQuery qo) {
        Query query = new Query();

        //条件查询
        if (qo.getDetailId() != -1) {
            query.addCriteria(Criteria.where("detailId").is(qo.getDetailId()));
        }

        //分页条件,不要忘记减一
        PageRequest pageRequest = PageRequest.of(qo.getCurrentPage() - 1, qo.getPageSize(),
                Sort.Direction.DESC, "createTime");

        long count = template.count(query, StrategyComment.class);

        query.with(pageRequest);

        List<StrategyComment> list = template.find(query, StrategyComment.class);

        return new PageImpl(list,pageRequest, count);
    }

    //用户点赞
    public void commentThumbUp(String toid, long fromid) {
        StrategyComment strategyComment = repository.findById(toid).get();
        if (strategyComment == null) {
            throw new LogicException("参数异常");
        }
        List<Long> thumbuplist = strategyComment.getThumbuplist();

        if (thumbuplist.contains(fromid)) {
            //如果包含用户的id
            //移除掉并且点赞数减一
            thumbuplist.remove(fromid);
            strategyComment.setThumbupnum(strategyComment.getThumbupnum() - 1);
        } else {
            //如果不包含用户的id
            //添加并且点赞数加一
            thumbuplist.add(fromid);
            strategyComment.setThumbupnum(strategyComment.getThumbupnum() + 1);
        }
        strategyComment.setThumbuplist(thumbuplist);
        repository.save(strategyComment);
    }

}
